package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    /**
     * 用户登录
     *
     * @param adUserDto
     * @return
     */

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //参数校验
        if (StringUtils.isEmpty(adUserDto.getName()) || StringUtils.isEmpty(adUserDto.getPassword())) {
            return ResponseResult.errorResult(500, "用户名和密码不能为空!!");
        }
        //查看数据库是否由此用户
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, adUserDto.getName());
        List<AdUser> list = list(queryWrapper);


        if (list != null && list.size() > 0) {
            //说明查到了数据,比对密码
            AdUser adUser = list.get(0);

            String pwd = DigestUtils.md5DigestAsHex((adUserDto.getPassword() + adUser.getSalt()).getBytes());
            if (adUser.getPassword().equals(pwd)) {
                String token = AppJwtUtil.getToken(adUser.getId().longValue());

                Map<String, Object> map = new HashMap<>();

                adUser.setPassword("");
                adUser.setSalt("");
                map.put("token", token);
                map.put("user", adUser);
                //将token保存到redis中去
               // redisTemplate.boundValueOps(adUser.getName()).set(token);
                return ResponseResult.okResult(map);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
    }
}
